<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px" @keyup.enter="submitHandle()">
			<el-form-item label="模板名称" prop="templateName">
				<el-input v-model="dataForm.templateName" placeholder="模板名称"></el-input>
			</el-form-item>
      <el-form-item label="模板标识" prop="templateType">
        <el-input v-model="dataForm.templateType" placeholder="模板名称"></el-input>
      </el-form-item>
      <el-form-item label="模板分组" prop="groupCode">
        <el-select v-model="dataForm.groupCode" placeholder="模板分组" style="width: 100%" clearable>
          <el-option v-for="item in groupCodeList" :key="item.codeId" :label="item.codeName" :value="item.codeId"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="生成文件路径" prop="templateRoute">
				<el-input v-model="dataForm.templateRoute" placeholder="生成文件路径"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {templateApi, templateSubmitApi} from '@/api/template'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
	id: '',
  templateName: '',
  templateType: '',
  groupCode: '',
  templateRoute: '',
  templateVersionId:undefined
})

const init = (id?: number,versionId?:any) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
		getTemplate(id)
	}
  //模板版本
  dataForm.templateVersionId = versionId
}

const getTemplate = (id: number) => {
  templateApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}

//模板分组
const groupCodeList=[
  {
    codeId:1,
    codeName: '前端'
  },
  {
    codeId:2,
    codeName: '后端'
  }
]

const dataRules = ref({
  templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  templateType: [{ required: true, message: '模板标识不能为空', trigger: 'blur' }],
  groupCode: [{ required: true, message: '模板分组不能为空', trigger: 'change' }],
  templateRoute: [{ required: true, message: '生成文件路径不能为空', trigger: 'blur' }],
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
    if(!dataForm.templateVersionId){
      ElMessage.warning("模板版本数据不能为空，请点击左边的模板版本")
      return
    }
    templateSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
